var express = require('express')
var app = express();
var db = require('./conn')
app.use((req, res, next) => {
    res.header("Access-Control-Allow-Credentials", true) 
    res.header('Access-Control-Allow-Origin', req.headers.origin)
    res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS') 
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With')
    next()
})
app.use(express.json())
app.use(express.urlencoded({ extended: false }));
app.use(express.static('./'))
app.post('/fruits/list', (req, res) => {
    var sql = 'select * from fruits'
    db.query(sql, [], (list, field) => {
        if (list) {
            res.send({
                success: true,
                msg: '成功',
                list
            })
        } else {
            res.send({
                success: false,
                msg: '失败'
            })
        }
    })
})
app.post('/fruits/add', (req, res) => {
    var sql = 'insert into fruits values(?,?,?,?)'
    db.query(sql, [, req.body.fruitName, req.body.fruitQuantity, req.body.fruitPrice], (list, field) => {
        if (list) {
            res.send({
                success: true,
                msg: '成功'
            })
        } else {
            res.send({
                success: false,
                msg: '失败'
            })
        }
    })
})
app.post('/fruits/del', (req, res) => {
    var sql = 'delete from fruits where id = ?'
    db.query(sql, [req.body.id], (list, field) => {
        if (list) {
            res.send({
                success: true,
                msg: '成功'
            })
        } else {
            res.send({
                success: false,
                msg: '失败'
            })
        }
    })
})
app.post('/fruits/update', (req, res) => {
    var sql = 'update fruits set fruitName=?,fruitQuantity=?,fruitPrice=? where id=?'
    db.query(sql, [req.body.fruitName, req.body.fruitQuantity, req.body.fruitPrice, req.body.id], (list, field) => {
        if (list) {
            res.send({
                success: true,
                msg: '成功'
            })
        } else {
            res.send({
                success: false,
                msg: '失败'
            })
        }
    })
})
app.listen(3000, () => {
    console.log('服务器OK！')
})